package registry

import (
	//"fmt"
	"gamesdk/common/log"

	consulapi "github.com/hashicorp/consul/api"
)

type consulRegistry struct {
	client *consulapi.Client
}

func (this *consulRegistry) PassTTL(nodeId string) error {
	return this.client.Agent().PassTTL("service:"+nodeId, "")
}
func (this *consulRegistry) ServiceRegister(reg *ServiceRegistration) error {
	var err error
	//如果服务已经存在
	services, _, err := this.client.Health().Checks(reg.Name, nil)
	if err == nil {
		for _, v := range services {
			if v.ServiceID == reg.ID {
				this.client.Agent().PassTTL("service:"+v.ServiceID, "")
				return nil
			}
		}
	}
	registration := new(consulapi.AgentServiceRegistration)
	registration.ID = reg.ID
	registration.Name = reg.Name
	registration.Port = reg.Port
	registration.Tags = reg.Tags
	registration.Address = reg.Address
	registration.Meta = reg.Meta
	registration.Check = &consulapi.AgentServiceCheck{
		//TCP: fmt.Sprintf("%s:%d", reg.Address, reg.Port),
		//Timeout: "3s",
		//Interval: "5s",
		TTL:                            "10s",
		DeregisterCriticalServiceAfter: "3s",
	}
	err = this.client.Agent().ServiceRegister(registration)
	if err != nil {
		log.Warn("register server error : %s", err.Error())
		return err
	}
	return nil
}

func (this *consulRegistry) ServiceDeregister(serviceID string) error {
	return this.client.Agent().ServiceDeregister(serviceID)
}

func (this *consulRegistry) Service(serviceID string) (*ServiceRegistration, error) {
	as, _, err := this.client.Agent().Service(serviceID, nil)
	if err != nil {
		return nil, err
	}
	sr := new(ServiceRegistration)
	sr.Address = as.Address
	sr.ID = as.ID
	sr.EnableTagOverride = as.EnableTagOverride
	sr.Meta = as.Meta
	sr.Name = serviceID
	sr.Port = as.Port
	sr.Tags = as.Tags
	return sr, nil
}
func (this *consulRegistry) Services(serviceName string) (*[]ServiceRegistration, error) {
	_, svrs, err := this.client.Agent().AgentHealthServiceByName(serviceName)
	if err != nil {
		return nil, err
	}
	srs := make([]ServiceRegistration, 0)
	for _, v := range svrs {
		sr := new(ServiceRegistration)
		sr.Address = v.Service.Address
		sr.ID = v.Service.ID
		sr.Name = v.Service.Service
		sr.EnableTagOverride = v.Service.EnableTagOverride
		sr.Meta = v.Service.Meta
		sr.Port = v.Service.Port
		sr.Tags = v.Service.Tags
		srs = append(srs, *sr)
	}
	return &srs, nil
}

func NewClient(addr string) (*Client, error) {
	var err error
	cli := new(Client)
	cr := new(consulRegistry)
	conf := consulapi.DefaultConfig()
	conf.Address = addr
	cr.client, err = consulapi.NewClient(conf)
	if err != nil {
		log.Warn("consul client error : %s", err.Error())
		return nil, err
	}
	cli.agent = cr
	return cli, err
}
